<script setup>
import { useStorage } from '@vueuse/core'
import { reverse, sortBy } from 'lodash-es';
import { io } from 'socket.io-client'
import short from 'short-uuid'
import { computed, onMounted, reactive, ref } from 'vue';
const userName = useStorage('my-username', '🌾' + Math.floor(Math.random() * 10000).toString())
const userId = useStorage('my-user-id', short.generate())
const roomId = useStorage('my-room-id', '')
const socket = io(import.meta.env.VITE_API);
const myScores = ref([])
const targetId = ref('')
const gameInfo = reactive({
    players: [],
    host: '',
    room: ''
})
const selected = reactive({
    you: -1,
    ta: -1
})

socket.emit('login', userId.value)
socket.on('sync', (state, host, room) => {
    gameInfo.players = state
    gameInfo.host = host
    gameInfo.room = room

    socket.emit('get-scores', userId.value, (scores) => {
        myScores.value = scores
    })
})
socket.on('notice',(message) => {
    alert(message)
})

function handleJoinRoom() {
    const room = prompt('请输入房间号')
    if (!room) return
    console.log(room)
    socket.emit('create-or-join-ninja-room', room, userName.value)
    roomId.value = room
}

function handleLeaveRoom() {
    socket.emit('logout')
    roomId.value = ''
    gameInfo.players = []
    gameInfo.host = ''
    gameInfo.room = ''
}

function handleDraw() { //抽分数
    socket.emit('draw')
}

function handleUndo() {
    socket.emit('undo')
}

function handleReset() {
    socket.emit('reset')
}

function handleSwap() {
    socket.emit('swap',userId.value,targetId.value,selected.you,selected.ta)
}

function handleEdit(){
    userName.value = prompt("编辑用户名")
    socket.emit('create-or-join-ninja-room', roomId.value, userName.value)
}

onMounted(() => {
    if (roomId.value) {
        socket.emit('create-or-join-ninja-room', roomId.value, userName.value)
    }
})

const sortedPlayers = computed(() => {
    return reverse(sortBy(gameInfo.players, 'scoresLength'))
})
</script>

<template>
    <div class="p-2 w-full ">
        <div>你的id：{{userId}}</div>
        <div class="flex items-center justify-between my-2">
            <div v-if="gameInfo.room">房间号：{{ gameInfo.room }}</div>
            <div v-else>大厅</div>
            <button @click="handleJoinRoom" class="btn" v-if="!gameInfo.room">加入房间</button>
            <button @click="handleLeaveRoom" class="btn" v-else>离开房间</button>
        </div>

        <label v-for="player in sortedPlayers" class="text-neutral-content transition-all duration-200 p-6 shadow mt-4 rounded-md w-full block"
            :class="player.isConnected ? ' bg-neutral' : 'bg-red-100'" for="modal-swap" @click="targetId = player.userId">
            <div class="flex justify-between">
                <p class="flex gap-2 items-center">
                    {{ player.userName }}
                    <span v-if="player.userId === userId" class=" badge badge-secondary">我</span>
                    <span v-if="player.userId === userId" class=" badge badge-secondary badge-outline" @click.prevent="handleEdit">编辑</span>
                </p>
                <p>
                    {{ player.scoresLength }}
                </p>
            </div>
            <div class="flex gap-2 mt-2" v-if="player.userId === userId">
                <div v-for="score in myScores"
                    class="rounded-full bg-primary w-10 h-10 flex justify-center items-center text-primary-content ">
                    {{ score }}
                </div>
            </div>
        </label>


    </div>
    <div class="fixed bottom-8 flex w-full justify-between p-2" v-if="gameInfo.room">
        <button @click="handleDraw" class="btn">抽取得分</button>
        <div class="flex gap-2">
            <button @click="handleUndo" class="btn btn-error">撤销</button>
            <button @click="handleReset" class="btn btn-accent" v-if="gameInfo.host === userId">重置</button>
        </div>
    </div>

    <Teleport to="html">
        <input type="checkbox" id="modal-swap" class="modal-toggle" />
        <label for="modal-swap" class="modal cursor-pointer">
            <label class="modal-box relative" for="">
                <p>TA的token</p>
                <div class="flex gap-2">
                    <button v-if="targetId"
                        v-for="i in gameInfo.players.find(player => player.userId === targetId).scoresLength"
                        class="rounded-full w-8 h-8 bg-primary border-2"
                        :class="selected.ta === i - 1? 'border-secondary' : 'border-transparent'"
                        @click="selected.ta = i - 1"></button>
                </div>
                <p>你的的token</p>
                <div class="flex gap-2">
                    <button v-for="(score, i) in myScores" class="rounded-full w-8 h-8 bg-primary border-2 text-primary-content"
                        :class="selected.you === i ? 'border-secondary' : 'border-transparent'" @click="selected.you = i">{{
                            score }}</button>
                </div>
                <div class="modal-action" v-if="selected.ta != -1 && selected.you != -1">
                    <label for="modal-swap" class="btn" @click="handleSwap">交换</label>
                </div>
            </label>
        </label>
    </Teleport>
</template>

<style scoped></style>
